package com.ydw;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Yangdw
 * @date 2025-09-02
 * @description:
 */
public class TransactionProducer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {

        TransactionMQProducer producer = new TransactionMQProducer("transaction_producer_group");


        producer.setNamesrvAddr("127.0.0.1:9876");

        producer.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
                //这里需要执行本地事务,如果本地事务成功的话,那么就返回成功
                //如果本地事务失败的话 那么就返回失败,则回滚事务



                return LocalTransactionState.ROLLBACK_MESSAGE;
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt msg) {

                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });

        producer.start();

        List<Message> messages = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (int i = 0; i < 12; i++) {
            JSONObject data = new JSONObject();
            data.put("date", LocalDateTime.now());
            data.put("message","你好好");
            data.put("datetime",dateTimeFormatter.format(LocalDateTime.now()));
            Message message = new Message(
                    "custom-batch-topic",
                    "batchTag",
                    data.toJSONString().getBytes(StandardCharsets.UTF_8)
            );
            messages.add(message);

        }
        producer.send(messages);
    }
}
